import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './withdraw.module.css';
import { useDispatch } from "react-redux";
import { Dialog, DotLoading, Mask, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";

import NavigateBar from "@/components/NavigateBar";
import BottomTabBar from "@/components/BottomTabBar/bottomTabBar";
import { extractInviteIncome, getInviteIncomeData } from "@/store/actions/user";
import { getCoinInfo, setWithdrawResultInfo } from "@/utils/storage";
import TransferPwdInput from "@/components/TransferInput/transferPwdInput";
import { LangThai } from "@/utils/langThai";


/**
 * 登录页
 */
export default function WithdrawForInvite() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // 当前 币
    const [curCoin, setCurCoin] = useState({})

    // 当前 收入数据
    const [curIncomeInfo, setCurIncomeInfo] = useState({})

    // 当前 输入 amount
    const [curAmount, setCurAmount] = useState("")

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    // 当前输入密码
    let curInputPassword = "";

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        // 获取当前币
        const coinInfo = getCoinInfo();
        const coninType = coinInfo.coinType || "";
        setCurCoin(coinInfo);

        // 获取邀请好友收益数据
        doGetInviteIncomeData(coninType);

        //打点
        doHitEvent("WITHDRAW_FOR_INVITE_START")

        return () => {
            //打点
            doHitEvent("WITHDRAW_FOR_INVITE_END")
        }
    }, [])


    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }



    // 获取邀请好友收益数据
    const doGetInviteIncomeData = async (coinType) => {
        console.log("doGetInviteIncomeData: ");
        console.log(coinType);

        if (!coinType || coinType.length <= 0) {
            Toast.show(curLang.withdrawTheCoinTypeCanNotBeNull);
            return;
        }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getInviteIncomeData(coinType, onDoGetInviteIncomeDataCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 提取邀请好友收益
    const doExtractInviteIncome = async () => {
        let curCoinType = curCoin.coinType || "";
        console.log("doGetInviteIncomeData: ");
        console.log("curCoinType: " + curCoinType);
        console.log("curInputPassword: " + curInputPassword);
        console.log("curAmount: " + curAmount);

        let curAmountF = parseFloat(curAmount) || 0;

        if (!curCoinType || curCoinType.length <= 0) {
            Toast.show(curLang.withdrawTheCoinTypeCanNotBeNull);
            return;
        }
        if (!curInputPassword || curInputPassword.length <= 6) {
            Toast.show(curLang.withdrawThePasswordIsNotCorrect);
            return;
        }
        if (curAmountF < 2) {
            Toast.show(curLang.withdrawTheWithdrawalAmountCannotBeLessThan2USDT);
            return;
        }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = extractInviteIncome(curCoinType, curInputPassword, curAmount, onDoExtractInviteIncomeCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取邀请好友收益数据 返回
    const onDoGetInviteIncomeDataCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取邀请好友收益数据 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            // {
            //     "canWithdrawAmount": "0E-8",
            //     "tomorrowCanWithdrawAmount": "0.00",
            //     "remindTimes": 3
            // }

            // 格式化
            let canWithdrawAmount = data.canWithdrawAmount || "0";
            data.canWithdrawAmount = parseFloat(canWithdrawAmount) || "0";

            // 刷新
            setCurIncomeInfo(data);
        }
    };

    // 提取邀请好友收益 返回
    const onDoExtractInviteIncomeCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('提取邀请好友收益 返回: ' + success);

        if (success && data) {
            // 处理流程业务

            let curCoinType = curCoin.coinType || "";
            let curAddress = curCoin.address || "";

            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            if (month < 10) {
                month = "0" + month;
            } else {
                month = "" + month;
            }

            let day = date.getDate();
            if (day < 10) {
                day = "0" + day;
            } else {
                day = "" + day;
            }
            let dateFormat = day + "/" + month + "/" + year;

            // 跳转 结果页
            let resultInfo = {
                coinType: curCoinType,
                amount: curAmount,
                address: curAddress,
                unit: "USDT",
                date: dateFormat
            }

            // 保存缓存
            setWithdrawResultInfo(resultInfo);

            // 清空
            setCurAmount("");

            // 跳转
            history.push('/withdrawresult');
        }
    };

    // 点击下一步
    const onHandleSubmit = () => {

        console.log('curIncomeInfo:');
        console.log(curIncomeInfo);

        let canWithdrawAmount = parseFloat(curIncomeInfo.canWithdrawAmount) || 0;
        if (canWithdrawAmount < 2) {
            Toast.show(curLang.withdrawTheWithdrawalAmountCannotBeLessThan2USDT);
            return;
        }

        // 显示交易密码框
        Dialog.alert({
            title: curLang.withdrawEnterPassword,
            content: <TransferPwdInput onInputChanged={(text) => {
                onHandleDialogInputChanged(text);
            }} />,
            confirmText: curLang.withdrawTransfer,
            onConfirm: () => {
                console.log("点击了确认：" + curInputPassword);
                // 发起提币
                doExtractInviteIncome();
            }
        });
    };


    const onHandleDialogInputChanged = (text) => {
        curInputPassword = text;
    };

    return (
        <div className="pageRoot pageBackgroundColorGray">
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{curLang.withdrawWithdraw}</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull">
                <div className={`${styles.withdrawContent}`}>
                    <div className={`${styles.withdrawMenuRow}`}>
                        <div className={styles.withdrawMenuRowTitle}>{curLang.withdrawForInviteAmountThatCanBeWithdrawn}</div>
                        <div className={styles.withdrawMenuRowValue}>{curIncomeInfo.canWithdrawAmount} USDT</div>
                    </div>
                </div>

                <div className={`${styles.withdrawContent} pageMarginTop10px`}>
                    <div className={`${styles.withdrawMenuRow}`}>
                        <div className={styles.withdrawMenuRowTitle}>Enter the withdrawal amount</div>
                        <div className={styles.withdrawMenuRowInput}>
                            <input className={styles.withdrawMenuRowInputValue}
                                value={curAmount}
                                onChange={e => { setCurAmount(e.target.value) }}
                                placeholder={curLang.withdrawNotLessThan2USDT}
                                type="number"
                                autoComplete="off" />
                        </div>
                    </div>

                    {/* 提交 */}
                    <div className="pageBtnSubmit pageMarginTop16px" onClick={onHandleSubmit}>Withdraw</div>

                    <div className={`${styles.withdrawMenuRowTips} pageMarginTop20px`}>{curLang.withdrawForInviteTips}</div>
                </div>
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"> </div>

            {/* tab bar */}
            <BottomTabBar page="earn" />

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}